package it.unisa.dao.implementation;

import java.sql.BatchUpdateException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import it.unisa.beans.Account;
import it.unisa.dao.AccountDao;

public class AccountHibernateDao extends HibernateDaoSupport
implements AccountDao {

	public boolean insert(Account account) {
		try{
		getHibernateTemplate().save(account);
		}
		catch(DataIntegrityViolationException e){
			return false;
		}
		return true;
		
	}

	public boolean update(Account account) {
		try {
			getHibernateTemplate().update(account);
			return true;
		}
		catch(DataAccessException d) { 
			return false;
		}
	}

	public void delete(String ssn) {
		Account account = (Account) getHibernateTemplate().get(
				Account.class, ssn);
		getHibernateTemplate().delete(account);
	}

	public List<Account> findAllAccounts() {
		return getHibernateTemplate().find("from Account");
	}

	public int accountCount() {
		return findAllAccounts().size();
	}
 
	public List<Account> find(Account a) {
		DetachedCriteria criteria =
				DetachedCriteria.forClass(Account.class);
		if(a.getOnline()!=-1)
			criteria.add(Restrictions.eq("online",a.getOnline()));
		if(a.getSsn()!=null)
			criteria.add(Restrictions.eq("ssn", a.getSsn()));
		if(a.getName()!=null)
			criteria.add(Restrictions.eq("name", a.getName()));
		if(a.getSurname()!=null)
			criteria.add(Restrictions.eq("surname", a.getSurname()));
		if(a.getEmail()!=null)
			criteria.add(Restrictions.eq("email", a.getEmail()));
		if(a.getNickname()!=null)
			criteria.add(Restrictions.eq("nickname",a.getNickname()));
		if(a.getPassword()!=null)
			criteria.add(Restrictions.eq("password",a.getPassword()));

		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return (List<Account>)getHibernateTemplate().
				findByCriteria(criteria);
	}



}
